import cv2
import time

width = 1280
height = 720

def capture_video_from_camera(device_path, display_delay=1):
    # 使用 OpenCV 初始化视频捕获
    cap = cv2.VideoCapture(device_path)

    if not cap.isOpened():
        print("Error: Cannot open camera")
        exit()

    # 设置分辨率，视频帧格式，帧率
    cap.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
    cap.set(cv2.CAP_PROP_FPS, 60)

    # 初始化帧率计算
    fps = 0
    prev_time = time.time()
    frame_count = 0

    try:
        while True:
            # 读取一帧
            ret, frame = cap.read()

            # 如果正确读取帧，ret为True
            if not ret:
                print("Can't receive frame (stream end?). Exiting ...")
                break

            # 显示结果帧
            cv2.imshow('Frame', frame)

            # 更新帧率计算
            current_time = time.time()
            frame_count += 1
            if (current_time - prev_time) > 1:
                fps = frame_count / (current_time - prev_time)
                print(f"FPS: {fps:.2f}")
                frame_count = 0
                prev_time = current_time

            # 按 'q' 键退出循环
            if cv2.waitKey(display_delay) & 0xFF == ord('q'):
                break

    finally:
        # 释放捕获
        cap.release()
        cv2.destroyAllWindows()

if __name__ == '__main__':
    device_path = '/dev/video0'
    capture_video_from_camera(device_path)